package com.atguigu.mySmartCampus.util;

import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class Upload{
    private static Map<String,Object> ERROR_RESULT = new HashMap();
    private static Map<String,Object> UPLOAD_RESULT = new HashMap();

    private static Map<String,Object> UploadPhoto(MultipartFile photo, String path){
        String originalName = photo.getOriginalFilename();

        int MAX_SIZE=20971520;
        File file = new File(path);
        if(!file.exists()){
            file.mkdirs();
        }
        if(photo.getSize()>MAX_SIZE){
            ERROR_RESULT.put("success",false);
            ERROR_RESULT.put("msg","上传的图片大小不能超过20M");
            return ERROR_RESULT;
        }

        String[] suffix = new String[]{".jpg",".JPG",".jpeg",".JPEG",".png",".PNG",".gif",".GIF",".bmp",".BMP"};
        SuffixFileFilter suffixFileFilter = new SuffixFileFilter(suffix);
        if(suffixFileFilter.accept(new File(file+originalName))){
             ERROR_RESULT.put("success", false);
            ERROR_RESULT.put("msg", "禁止上传此类型文件! 请上传图片哟!");
            return ERROR_RESULT;
        }
        return null;
    }

    public static Map<String,Object> getUploadResult(MultipartFile photo,String dirPath,String portraitPath){
        if(!photo.isEmpty()&&photo.getSize()>0){
            String originalName = photo.getOriginalFilename();
            Map<String,Object> result = Upload.UploadPhoto(photo,dirPath);
            if(result !=null) {return result;}
            String photoNewName = UUID.randomUUID()+"__"+originalName;
            try {
                photo.transferTo(new File(dirPath+photoNewName));
                UPLOAD_RESULT.put("success",true);
                UPLOAD_RESULT.put("portrait_path",portraitPath+photoNewName);
            } catch (IOException e) {
                e.printStackTrace();
                UPLOAD_RESULT.put("success",false);
                UPLOAD_RESULT.put("msg","上传文件失败! 服务器端发生异常");

            }
        }else{
            UPLOAD_RESULT.put("success",false);
            UPLOAD_RESULT.put("msg","头像上传失败! 未找到指定图片");
        }
        return UPLOAD_RESULT;
    }     
}
